import { _decorator, Component, EventTouch, Node, UITransform, v2, v3, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass
export default class FollowTouch extends Component {
    // 用于存储触摸点的世界坐标
    private touchPos: Vec2 = v2(0, 0);
    // 用于标记是否正在触摸
    private isTouching: boolean = false;

    public touchMoveCb: () => void;

    onLoad() {
        // 监听触摸开始事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        // 监听触摸移动事件
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        // 监听触摸结束事件
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onDestroy() {
        // 移除触摸事件监听
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onTouchStart(event: EventTouch) {
        // 标记为正在触摸
        this.isTouching = true;

        // 获取触摸点的世界坐标
        this.touchPos = event.getUILocation();

        // 将世界坐标转换为节点坐标
        let nodePos = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(v3(this.touchPos.x, this.touchPos.y, 0));
        // 更新 UI 元素的位置
        this.node.setPosition(nodePos);
    }

    onTouchMove(event: EventTouch) {
        if (!this.isTouching) return;

        this.touchMoveCb();

        // 获取触摸点的世界坐标
        this.touchPos = event.getUILocation();

        // 将世界坐标转换为节点坐标
        let nodePos = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(v3(this.touchPos.x, this.touchPos.y, 0));

        // 更新 UI 元素的位置
        this.node.setPosition(nodePos);
    }

    onTouchEnd(event: EventTouch) {
        // 标记为触摸结束
        this.isTouching = false;
    }
}

